/*
 * Copyright 2008-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.hasor.dataway.web;

import com.alibaba.druid.sql.SQLUtils;
import net.hasor.dataway.authorization.AuthorizationType;
import net.hasor.dataway.authorization.RefAuthorization;
import net.hasor.dataway.config.MappingToUrl;
import net.hasor.dataway.config.Result;
import net.hasor.dataway.dal.ApiStatusEnum;
import net.hasor.dataway.dal.EntityDef;
import net.hasor.dataway.dal.FieldDef;
import net.hasor.utils.CommonCodeUtils;
import net.hasor.web.annotation.Get;
import net.hasor.web.objects.JsonRenderEngine;
import net.hasor.web.render.RenderType;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Api 列表
 *
 * @author 赵永春 (zyc@hasor.net)
 * @version : 2020-03-24
 */
@MappingToUrl("/api/api-list")
@RefAuthorization(AuthorizationType.ApiList)
@RenderType(value = "json", engineType = JsonRenderEngine.class)
public class ApiListController extends BasicController {
    protected static Logger logger = LoggerFactory.getLogger(ApiInfoController.class);
    public static SQLUtils.FormatOption DEFAULT_FORMAT_OPTION;

    @Get
    public Result<List<Map<String, Object>>> apiList() {
        List<Map<FieldDef, String>> infoList = this.dataAccessLayer.listObjectBy(//
                EntityDef.INFO, //
                emptyCondition()//
        );
        infoList = (infoList == null) ? Collections.emptyList() : infoList;
        //
        List<Map<String, Object>> dataList = infoList.parallelStream()//
                .map((Function<Map<FieldDef, String>, Map<String, Object>>) infoMap -> {
                    return new HashMap<String, Object>() {{
                        put("id", infoMap.get(FieldDef.ID));
                        put("checked", false);
                        put("select", infoMap.get(FieldDef.METHOD));
                        put("path", infoMap.get(FieldDef.PATH));
                        put("status", ApiStatusEnum.typeOf(infoMap.get(FieldDef.STATUS)).typeNum());
                        put("comment", infoMap.get(FieldDef.COMMENT));
                    }};
                }).collect(Collectors.toList());
        return Result.of(dataList);
    }

    @Get
    public Result<String> apiBackup() {
        try {
            String backupUrl = "";
            // 将两张表的数据查询出来，并生成 SQL 语句，最后打包成 zip 文件，并提供下载 URL
            String text = "";
            text += parseSqls(EntityDef.INFO);
            text += parseSqls(EntityDef.RELEASE);
            String sqlFilePath = ApiListController.class.getResource("/").toURI().getPath();
            String hash = CommonCodeUtils.MD5.getMD5(text + System.currentTimeMillis());
            String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String relativePath = "/download/backup_" + date + "_" + hash;
            sqlFilePath += "/static" + relativePath;
            File sqlFile = new File(sqlFilePath + ".sql");
            if (!sqlFile.exists()) {
                FileUtils.forceMkdir(sqlFile.getParentFile());
            }
            FileUtils.writeStringToFile(sqlFile, text, "utf-8");
            try (ZipOutputStream zipOutputStream = new ZipOutputStream(
                    new FileOutputStream(sqlFilePath + ".zip"));
                 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sqlFile));
                 BufferedOutputStream bos = new BufferedOutputStream(zipOutputStream);
            ) {
                zipOutputStream.putNextEntry(new ZipEntry("/"));
                int tag;
                //将源文件写入到zip文件中
                while ((tag = bis.read()) != -1) {
                    bos.write(tag);
                }
            }
            backupUrl = relativePath + ".zip";
            return Result.of(backupUrl);
        } catch (Exception e) {
            logger.error("备份 API 表异常", e);
            return Result.of(-1, e.getMessage());
        }
    }

    /**
     * @param entityDef 定义的表
     * @return 入库语句
     */
    private String parseSqls(EntityDef entityDef) {
        List<Map<FieldDef, String>> infoList = this.dataAccessLayer.listObjectBy(//
                entityDef, //
                emptyCondition()//
        );
        infoList = (infoList == null) ? Collections.emptyList() : infoList;
        String table;
        if (entityDef.equals(EntityDef.INFO)) {
            table = "interface_info";
        } else if (entityDef.equals(EntityDef.RELEASE)) {
            table = "interface_release";
        } else {
            throw new RuntimeException("不支持的表类型");
        }
        table = quoteObj(table);
        StringBuilder sb = new StringBuilder("truncate table `" + table + "`;\n");
        for (Map<FieldDef, String> row : infoList) {
            List<String> keys = new ArrayList<>();
            List<Object> vals = new ArrayList<>();
            row.forEach((key, val) -> {
                keys.add(quoteObj(key.name()));
            });
            String keysJoin = StringUtils.join(keys, ",");
            String valsHolder = StringUtils.repeat(",?", keys.size()).substring(1);
            String sql = "insert into " + table + " (" + keysJoin + ") values(" + valsHolder + ");";
            sb.append(formattedSql(sql, vals)).append("\n");
        }
        return sb.toString();
    }

    /**
     * @param obj 数据库中的对象名
     * @return 添加引号之后的对象名
     */
    private String quoteObj(String obj) {
        return "`" + obj + "`";
    }

    /**
     * @param sql    值对象
     * @param params 对应 “?” 的参数
     * @return 转义后的值对象
     */
    private String formattedSql(String sql, List<Object> params) {
        return SQLUtils.format(sql, "mysql", params, DEFAULT_FORMAT_OPTION);
    }
}